import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import shp from "shpjs";
import GeoJSON from "ol/format/GeoJSON"
import { Fill, Stroke, Style } from 'ol/style';


export async function loadShapefiles(fileZipPath) {
    const response = await fetch(fileZipPath);
    const blob = await response.blob();

    const arrayBuffer = await new Promise((resolve, reject) => {
        // debugger
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsArrayBuffer(blob);
    });
    console.log(arrayBuffer);
    try {
        // debugger
        const geojson = await shp(arrayBuffer);
        const vectorSource = new VectorSource()
        geojson.forEach(item => {
            // debugger
            const features = new GeoJSON().readFeatures(item, {
                featureProjection: "EPSG:3857", // 目标投影是WEB Mercator
                dataProjection: "EPSG:4326",  // 源数据投影是WGS 84
            })

            // 遍历要素，设置多边形的样式
            features.forEach(feature => {

                if (feature.getGeometry().getType() === 'Polygon') {
                    feature.setStyle(new Style({
                        fill: new Fill({
                            color: 'rgba(0, 255, 0, 0.5)' // 半透明红色
                        }),
                        stroke: new Stroke({
                            color: 'green',
                            width: 2
                        })
                    }));
                }

                // // 获取多边形的 extent
                // const extent = feature.getGeometry().getExtent();
                // console.log(extent);
                
            });
            vectorSource.addFeatures(features)
        });

        return new VectorLayer({
            zIndex: 10,
            source: vectorSource
        })

    } catch (error) {
        console.error('Error loading shapefile:', error);
    }

}

